var fs = require('fs');

function get_file_contents(filepath) {
	try {
		if (fs.existsSync(filepath)) {
			return fs.readFileSync(filepath, 'utf8');
		} else {
			return '';
		}
	} catch(err) {
		console.error(err);
	}
}

var info = JSON.parse(get_file_contents('src/info.json'));
var html = get_file_contents('src/html/index.html');
var menu_item_template = get_file_contents('src/html/menu_item.html');
var column_headers_template = get_file_contents('src/html/column_headers.html');
var code_rows_template = get_file_contents('src/html/code_rows.html');
var code_cell_template = get_file_contents('src/html/code_cell.html');

// Process Languages
if ( info.languages ) {
	var output_queue, output_queue2;
	var output, output2;

	// Process menu items
	output_queue = '';
	info.languages.forEach(function(lang) {
		output = menu_item_template;
		//console.log(lang);
		if ( info.default_langs.includes(lang.slug) ) {
			output = output.replace(/{{_ checked _}}/g, 'checked');
		} else {
			output = output.replace(/{{_ checked _}}/g, '');
		}
		output = output.replace(/{{_ slug _}}/g, lang.slug)
		output = output.replace(/{{_ label _}}/g, lang.label)
		output_queue += output;
	});
	html = html.replace(/{{_ menu_items _}}/g, output_queue);

	// Process columns
	output_queue = '';
	info.languages.forEach(function(lang) {
		output = column_headers_template;
		if ( info.default_langs.includes(lang.slug) ) {
			output = output.replace(/{{_ hidden _}}/g, '');
		} else {
			output = output.replace(/{{_ hidden _}}/g, 'hidden');
		}
		output = output.replace(/{{_ slug _}}/g, lang.slug);
		output = output.replace(/{{_ label _}}/g, lang.label);
		output_queue += output;
	});
	html = html.replace(/{{_ column_headers _}}/g, output_queue);
}

// Process codes
if ( info.codes ) {
	output_queue = '';
	info.codes.forEach(function(code) {
		output = code_rows_template;
		output = output.replace(/{{_ code_label _}}/g, code.label);
		// Code cells
		output_queue2 = '';
		info.languages.forEach(function(lang) {
			output2 = code_cell_template;
			if ( info.default_langs.includes(lang.slug) ) {
				output2 = output2.replace(/{{_ hidden _}}/g, '');
			} else {
				output2 = output2.replace(/{{_ hidden _}}/g, 'hidden');
			}
			output2 = output2.replace(/{{_ slug _}}/g, lang.slug);
			output2 = output2.replace(/{{_ label _}}/g, lang.label);
			output2 = output2.replace(/{{_ code _}}/g, get_file_contents('src/codes/'+lang.slug+'/'+code.slug+'.'+lang.ext));
			output_queue2 += output2;
		});
		output = output.replace(/{{_ code_cells _}}/g, output_queue2);
		output_queue += output;
	});
}
html = html.replace(/{{_ code_rows _}}/g, output_queue);

// Write index.html
try {
	const data = fs.writeFileSync('public/index.html', html)
} catch (err) {
	console.error(err)
}
